package com.klhappy.houyuan.utils.imageselector;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.klhappy.houyuan.R;
import com.klhappy.houyuan.view.banner.DisplayUtil;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片的目录详细页
 *
 */
public class ImageGridActivity extends Activity implements OnClickListener {
	public static final String EXTRA_IMAGE_LIST = "imagelist";
	
	private List<ImageBucket> contentList;
	private RelativeLayout title;
	
	private List<ImageItem> dataList;
	private GridView gridView;
	private ImageGridAdapter adapter;
	private AlbumHelper helper;
	private Button bt;
	private int count = 0;
	
	private TextView tv_cancel;
	private TextView tv_content;
	private PopupWindow pop = null;
	private ListView popListView = null;
	private boolean isFull = false;
	
	private BitmapCache cache = new BitmapCache();
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					if (!isFull) {
						Toast.makeText(ImageGridActivity.this, "最多选择9张图片", Toast.LENGTH_SHORT).show();
						isFull = true;
					}
					break;
	
				default:
					break;
			}
		}
	};
	
	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_grid_img_selector);
		
		helper = AlbumHelper.getHelper();
		helper.init(getApplicationContext());
		
		contentList = helper.getImagesBucketList(false);
		dataList = new ArrayList<>();
		for(int i = 0; i < contentList.size(); i++){
			dataList.addAll(contentList.get(i).imageList);
		}
		
		Bimp.tempSelectBitmap.clear();
		Bimp.tempSelectBitmap.addAll(Bimp.selectBitmap);
		
		ImageBucket bucket = new ImageBucket();
		bucket.bucketName = "所有图片";
		bucket.imageList = dataList;
		bucket.count = bucket.imageList.size();
		contentList.add(0, bucket);
		
		initView();

	}

	private void initView() {
		title = (RelativeLayout) findViewById(R.id.title);
		
		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new ImageGridAdapter();
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				adapter.notifyDataSetChanged();
			}
		});
		
		bt = (Button) findViewById(R.id.bt);
		count = Bimp.tempSelectBitmap.size();
		bt.setText("完成" + "(" + count + "/9)");
		bt.setOnClickListener(this);
		
		tv_cancel = (TextView) findViewById(R.id.tv_cancel);
		tv_cancel.setOnClickListener(this);
		
		tv_content = (TextView) findViewById(R.id.tv_content);
		tv_content.setOnClickListener(this);
		
		View popLayout = getLayoutInflater().inflate(R.layout.poplayout_img_selector, null);
		pop = new PopupWindow(popLayout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setAnimationStyle(R.style.PopupAnimation1_img_selector);
		popListView = (ListView) popLayout.findViewById(R.id.lv_content);
		popListView.setAdapter(new MyAdapter());
		popListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				dataList = contentList.get(arg2).imageList;
				adapter.notifyDataSetChanged();
				pop.dismiss();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
			case R.id.tv_cancel:
				finish();
				overridePendingTransition(R.anim.translate_in_img_selector, R.anim.translate_out_img_selector);
				break;
			case R.id.bt:
				Bimp.selectBitmap.clear();
				Bimp.selectBitmap.addAll(Bimp.tempSelectBitmap);
				finish();
				overridePendingTransition(R.anim.translate_in_img_selector, R.anim.translate_out_img_selector);
				break;
			case R.id.tv_content:
				pop.showAsDropDown(title);
				break;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Bimp.tempSelectBitmap.clear();//清空临时选择图片列表
	}
	
	
	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return contentList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			// TODO Auto-generated method stub
			if(view == null){
				view = getLayoutInflater().inflate(R.layout.poplayoutitem_img_selector, null);
			}

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			

			tv_content.setText(contentList.get(position).bucketName + "(" + contentList.get(position).count + ")");
			
			return view;
		}
		
	}
	
	class ImageGridAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			int count = 0;
			if (dataList != null) {
				count = dataList.size();
			}
			return count;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		class Holder {
			private ImageView iv;
			private ImageView selected;
			private TextView text;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final Holder holder;

			if (convertView == null) {
				holder = new Holder();
				convertView = getLayoutInflater().inflate(R.layout.item_image_grid_img_selector, null);
				holder.iv = (ImageView) convertView.findViewById(R.id.image);
				holder.selected = (ImageView) convertView
						.findViewById(R.id.isselected);
				holder.text = (TextView) convertView
						.findViewById(R.id.item_image_grid_text);
				convertView.setTag(holder);
				holder.text.setBackgroundColor(0x00000000);
				holder.selected.setImageResource(R.drawable.plugin_camera_choosed); 
			} else {
				holder = (Holder) convertView.getTag();
			}
			
			dataList.get(position).isSelected = false;
			if (Bimp.tempSelectBitmap.size() > 0) {//关联已选中图片的显示
				for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
					if (dataList.get(position).imageId.equals(Bimp.tempSelectBitmap.get(i).imageId)) {
						dataList.get(position).isSelected = true;
						break;
					}
				}
			}
			
			
			final ImageItem item = dataList.get(position);
			
			String path = "";//判断图片是否存在
            if (!TextUtils.isEmpty(item.getImagePath()) && FileUtils.fileIsExists(item.getImagePath())) {
                path = item.getImagePath();
            }else {
                dataList.remove(position);
                notifyDataSetChanged();
                return convertView;
            }
			
			holder.iv.setTag(item.imagePath);
			int size = DisplayUtil.getWindowWidth(ImageGridActivity.this) / 6;
			Picasso.with(ImageGridActivity.this)
					.load(new File(path))
					.placeholder(R.drawable.default_img)
					.error(R.drawable.default_img)
					.centerCrop()
					.resize(size, size)
					.into(holder.iv);
			
			if (item.isSelected) {
				holder.selected.setVisibility(View.VISIBLE);
			} else {
				holder.selected.setVisibility(View.INVISIBLE);
			}
			holder.iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (Bimp.tempSelectBitmap.size() < 9 ) {
						item.isSelected = !item.isSelected;
						if (item.isSelected) {
							holder.selected.setVisibility(View.VISIBLE);
							dataList.get(position).setSelected(true);
							Bimp.tempSelectBitmap.add(dataList.get(position));
						} else if (!item.isSelected) {
							holder.selected.setVisibility(View.INVISIBLE);
							dataList.get(position).setSelected(false);
							removePic(position);
						}
						bt.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/9)");
					} else if (Bimp.tempSelectBitmap.size() >= 9) {
						if (item.isSelected == true) {
							item.isSelected = !item.isSelected;
							holder.selected.setVisibility(View.INVISIBLE);
							dataList.get(position).setSelected(false);
							removePic(position);
							bt.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/9)");
						} else {
							Message message = Message.obtain(mHandler, 0);
							message.sendToTarget();
						}
					}
				}

			});

			return convertView;
		}
		
		private void removePic(int position) {
			for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
				if (dataList.get(position).imageId.equals(Bimp.tempSelectBitmap.get(i).imageId)) {
					Bimp.tempSelectBitmap.remove(i);
					if (isFull) {
						isFull = false;
					}
				}
			}
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if(pop.isShowing()){
			pop.dismiss();
		}
		return super.onTouchEvent(event);
	}
	
}
